package com.bjpowernode.dataservice.service.impl;

import com.bjpowernode.api.model.BidInfo;
import com.bjpowernode.api.model.FinanceAccount;
import com.bjpowernode.api.model.ProductInfo;
import com.bjpowernode.api.result.DubboResult;
import com.bjpowernode.api.service.InvestService;
import com.bjpowernode.api.vo.ProductBidInfo;
import com.bjpowernode.contacts.YLBConst;
import com.bjpowernode.dataservice.mapper.BidInfoMapper;
import com.bjpowernode.dataservice.mapper.FinanceAccountMapper;
import com.bjpowernode.dataservice.mapper.ProductInfoMapper;
import com.bjpowernode.enums.Code;
import com.bjpowernode.utils.DecimalUtil;
import com.sun.scenario.effect.Offset;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: panDeng_Zhu
 * @time: 2022/10/26 19:10
 */

@DubboService(interfaceClass = InvestService.class, version = "1.0")
public class InvestServiceImpl implements InvestService {

    @Resource
    private BidInfoMapper bidInfoMapper;

    @Resource
    private FinanceAccountMapper accountMapper;

    @Resource
    private ProductInfoMapper infoMapper;

    //查询某个产品的投资记录
    @Override
    public List<ProductBidInfo> queryBidListByProductId(Integer productId, Integer pageNo, Integer pageSize) {

        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 0) {
            pageSize = 5;
        }
        int offset = (pageNo - 1) * pageSize;
        List<ProductBidInfo> list = bidInfoMapper.selectProductByProductId(productId, offset, pageSize);
        return list;
    }

    //投资理财产品
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DubboResult investProduct(Integer userId, Integer productId, Integer money) {
        int rows = 0;
        DubboResult result = new DubboResult();
        //1.查询用户资金
        FinanceAccount account = accountMapper.selectByUserIdForUpdate(userId);
        if (account != null) {
            BigDecimal investMoney = new BigDecimal(money);
            //2.判断资金账号
            if (DecimalUtil.bigDecimal(account.getAvailableMoney(), investMoney)) {//账户剩余金额大于投资金额
                //3.判断产品数据
                ProductInfo product = infoMapper.selectByPrimaryKey(productId);
                if (product != null && product.getProductStatus() == YLBConst.INVEST_PRODUCT_SELL) {//产品存在并且可投资
                    //判断 money是否符合产品要求，min，max，left
                    if (DecimalUtil.bigDecimal(investMoney, product.getBidMinLimit()) &&
                            DecimalUtil.bigDecimal(product.getBidMaxLimit(), investMoney) &&
                            DecimalUtil.bigDecimal(product.getLeftProductMoney(), investMoney)) {
                        //投资金额有效
                        //4.扣除账号资金
                        rows = accountMapper.updateInvest(userId, investMoney);
                        if (rows < 1) {
                            throw new RuntimeException("投资产品，扣除账号余额失败");
                        }
                        //5.扣除产品剩余可投资金额

                        rows = infoMapper.updateInvest(productId, investMoney);
                        if (rows < 1) {
                            throw new RuntimeException("投资产品，扣除产品剩余可投资金额失败");
                        }
                        //6.生成投资记录
                        BidInfo info = new BidInfo();
                        info.setUid(userId);
                        info.setBidStatus(YLBConst.BID_STATUS_PRODUCT_SUCCESS);
                        info.setBidTime(new Date());
                        info.setBidMoney(investMoney);
                        info.setProdId(productId);
                        bidInfoMapper.insertSelective(info);

                        //7.判断产品是否满标，如果满标更新产品的状态
                        ProductInfo productInfo = infoMapper.selectByPrimaryKey(productId);
                        if (productInfo.getLeftProductMoney().compareTo(new BigDecimal("0")) == 0) {
                            productInfo.setProductStatus(YLBConst.INVEST_PRODUCT_SELLED);
                            productInfo.setProductFullTime(new Date());
                            rows = infoMapper.updateByPrimaryKeySelective(productInfo);
                            if (rows < 1) {
                                throw new RuntimeException("投资产品失败，更新产品状态失败");
                            }
                        }
                        //成功的标志
                        result.setInvoke(true);
                        result.setCode(1000);
                        result.setMsg("投资成功");
                    } else {
                        result.setCode(1004);
                        result.setMsg("投资失败，投资金额没有满足产品要求");
                    }
                } else {
                    result.setCode(1003);
                    result.setMsg("投资失败，产品不存在");
                }
            } else {
                result.setCode(1002);
                result.setMsg("投资失败，账号资金不足");
            }
        } else {
            result.setCode(1001);
            result.setMsg("投资失败，没有此账号");
        }
        return result;
    }

    //分页查询投资记录
    @Override
    public List<ProductBidInfo> queryBidListByUserId(Integer userId, Integer pageNo, Integer pageSize) {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 0) {
            pageSize = 5;
        }
        int offset = (pageNo - 1) * pageSize;
        List<ProductBidInfo> productBidInfoList = bidInfoMapper.selectBidListByUserId(userId, offset, pageSize);
        return productBidInfoList;
    }
}
